package com.wzc.hc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzc.hc.entity.po.Building;
import com.wzc.hc.entity.po.House;
import com.wzc.hc.entity.po.Owner;
import com.wzc.hc.entity.po.Unit;
import com.wzc.hc.entity.req.HouseSelectReq;
import com.wzc.hc.entity.resp.Result;
import com.wzc.hc.entity.vo.HouseVo;
import com.wzc.hc.service.BuildingService;
import com.wzc.hc.service.HouseService;
import com.wzc.hc.service.OwnerService;
import com.wzc.hc.service.UnitService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/*
    @author: m1825
    @date: 2025/3/3 17:03
*/
@Tag(name = "房屋")
@RestController
@RequestMapping("/house")
public class HouseController {
    @Resource
    private OwnerService ownerService;
    @Resource
    private HouseService houseService;
    @Resource
    private UnitService unitService;
    @Resource
    private BuildingService buildingService;

    @Operation(summary = "新增楼栋")
    @PostMapping("/addBuilding")
    public Result<Boolean> addBuilding(@RequestBody Building building) {
        try {
            building.setBuildingCommunityId("1");
            return Result.ok(buildingService.save(building));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "新增单元")
    @PostMapping("/addUnit")
    public Result<Boolean> addUnit(@RequestBody Unit unit) {
        try {
            return Result.ok(unitService.save(unit));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "新增房屋")
    @PostMapping("/addHouse")
    public Result<Boolean> addHouse(@RequestBody House house) {
        try {
            return Result.ok(houseService.save(house));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "查看楼栋")
    @GetMapping("/listBuilding")
    public Result<List<Building>> listBuilding() {
        try {
            return Result.ok(buildingService.list());
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "查看单元")
    @GetMapping("/listUnitByBuildingId")
    public Result<List<Unit>> listUnitByBuildingId(@RequestParam(value = "BuildingId") String id) {
        try {
            QueryWrapper<Unit> wrapper = new QueryWrapper<>();
            wrapper.eq("unit_building_id", id);
            return Result.ok(unitService.list(wrapper));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "根据单元分页查看房屋")
    @GetMapping("/pageHouseByUnitId")
    public Result<Page<HouseVo>> pageHouseByUnitId(@RequestParam(value = "UnitId") String id,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                   @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        try {
            Unit unit = unitService.getById(id);
            Building building = buildingService.getById(unit.getUnitBuildingId());
            QueryWrapper<House> wrapper = new QueryWrapper<>();
            wrapper.eq("house_unit_id", id);
            Page<House> housePage = houseService.page(new Page<>(pageNum, pageSize), wrapper);
            List<House> houses = housePage.getRecords();
            List<HouseVo> houseVoList = houses.stream().map(house -> new HouseVo(building, unit, house, null)).toList();
            houseVoList.forEach(houseVo -> {
                String houseOwnerId = houseVo.getHouse().getHouseOwnerId();
                if (houseOwnerId == null)
                    return;
                houseVo.setOwner(ownerService.getById(houseOwnerId));
            });
            Page<HouseVo> houseVoPage = new Page<>(housePage.getCurrent(), housePage.getSize(), housePage.getTotal());
            houseVoPage.setRecords(houseVoList);
            return Result.ok(houseVoPage);
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "根据楼栋分页查看房屋")
    @GetMapping("/pageHouseByBuildingId")
    public Result<Page<HouseVo>> pageHouseByBuildingId(@RequestParam(value = "BuildingId") String id,
                                                       @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                       @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        try {
            Building building = buildingService.getById(id);
            QueryWrapper<Unit> unitQueryWrapper = new QueryWrapper<>();
            unitQueryWrapper.eq("unit_building_id", id);
            List<Unit> units = unitService.list(unitQueryWrapper);
            if (units.isEmpty())
                return Result.fail();
            List<String> list = units.stream().map(Unit::getId).toList();
            QueryWrapper<House> wrapper = new QueryWrapper<>();
            wrapper.in("house_unit_id", list);
            Page<House> page = new Page<>(pageNum, pageSize);
            Page<House> housePage = houseService.page(page, wrapper);
            List<HouseVo> houseVoList = housePage.getRecords().stream().map(house -> new HouseVo(building, null, house, null)).toList();
            houseVoList.forEach(houseVo -> {
                for (Unit unit : units) {
                    if (houseVo.getHouse().getHouseUnitId().equals(unit.getId())) {
                        houseVo.setUnit(unit);
                        String houseOwnerId = houseVo.getHouse().getHouseOwnerId();
                        if (houseOwnerId == null)
                            return;
                        houseVo.setOwner(ownerService.getById(houseOwnerId));
                        return;
                    }
                }
            });
            Page<HouseVo> houseVoPage = new Page<>(housePage.getCurrent(), housePage.getSize(), housePage.getTotal());
            houseVoPage.setRecords(houseVoList);
            return Result.ok(houseVoPage);
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "查询房屋")
    @PostMapping("/selectHouse")
    public Result<Page<HouseVo>> selectHouse(@RequestBody HouseSelectReq houseSelectReq,
                                             @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        try {
            ArrayList<HouseVo> houseVos = new ArrayList<>();
            QueryWrapper<House> houseQueryWrapper = new QueryWrapper<>();
            if (houseSelectReq.getBuildingSerial() != null) {
                QueryWrapper<Building> buildingQueryWrapper = new QueryWrapper<>();
                buildingQueryWrapper.eq("building_serial", houseSelectReq.getBuildingSerial());
                Building building = buildingService.getOne(buildingQueryWrapper);
                QueryWrapper<Unit> unitQueryWrapper = new QueryWrapper<>();
                unitQueryWrapper.eq("unit_serial", houseSelectReq.getUnitSerial());
                unitQueryWrapper.eq("unit_building_id", building.getId());
                Unit unit = unitService.getOne(unitQueryWrapper);
                houseQueryWrapper.eq("house_serial", houseSelectReq.getHouseSerial());
                houseQueryWrapper.eq("house_unit_id", unit.getId());
                House house = houseService.getOne(houseQueryWrapper);
                Owner owner = ownerService.getById(house.getHouseOwnerId());
                houseVos.add(new HouseVo(building, unit, house, owner));
                Page<HouseVo> houseVoPage = new Page<>(pageNum, pageSize, 1);
                return Result.ok(houseVoPage.setRecords(houseVos));
            }
            if (houseSelectReq.getHouseType() != null)
                houseQueryWrapper.eq("house_type", houseSelectReq.getHouseType());
            if (houseSelectReq.getHouseState() != null)
                houseQueryWrapper.eq("house_state", houseSelectReq.getHouseState());
            Page<House> page = new Page<>(pageNum, pageSize);
            Page<House> housePage = houseService.page(page, houseQueryWrapper);
            housePage.getRecords().forEach(house -> {
                Unit unit = unitService.getById(house.getHouseUnitId());
                Building building = buildingService.getById(unit.getUnitBuildingId());
                Owner owner = ownerService.getById(house.getHouseOwnerId());
                houseVos.add(new HouseVo(building, unit, house, owner));
            });
            Page<HouseVo> houseVoPage = new Page<>(pageNum, pageSize, housePage.getTotal());
            houseVoPage.setRecords(houseVos);
            return Result.ok(houseVoPage);
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "删除楼栋")
    @DeleteMapping("/deleteBuilding")
    public Result<Boolean> deleteBuilding(@RequestParam(value = "BuildingId") String id) {
        try {
            QueryWrapper<Unit> wrapper = new QueryWrapper<>();
            wrapper.eq("unit_building_id", id);
            List<Unit> units = unitService.list(wrapper);
            units.forEach(unit -> deleteUnit(unit.getId()));
            return Result.ok(buildingService.removeById(id));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "删除单元")
    @DeleteMapping("/deleteUnit")
    public Result<Boolean> deleteUnit(@RequestParam(value = "UnitId") String id) {
        try {
            QueryWrapper<House> wrapper = new QueryWrapper<>();
            wrapper.eq("house_unit_id", id);
            List<House> houses = houseService.list(wrapper);
            houses.forEach(house -> deleteHouse(house.getId()));
            return Result.ok(unitService.removeById(id));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "删除房屋")
    @DeleteMapping("/deleteHouse")
    public Result<Boolean> deleteHouse(@RequestParam(value = "HouseId") String id) {
        try {
            return Result.ok(houseService.removeById(id));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "更新楼栋")
    @PutMapping("/updateBuilding")
    public Result<Boolean> updateBuilding(@RequestBody Building building) {
        try {
            return Result.ok(buildingService.updateById(building));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "更新单元")
    @PutMapping("/updateUnit")
    public Result<Boolean> updateUnit(@RequestBody Unit unit) {
        try {
            return Result.ok(unitService.updateById(unit));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "更新房屋")
    @PutMapping("/updateHouse")
    public Result<Boolean> updateHouse(@RequestBody House house) {
        try {
            return Result.ok(houseService.updateById(house));
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "交房")
    @PostMapping("/handoverOfHouse")
    public Result<Object> handoverOfHouse(@RequestParam(value = "ownerId") String ownerId,
                                          @RequestParam(value = "houseId") String houseId) {
        try {
            House house = houseService.getById(houseId);
            house.setHouseOwnerId(ownerId);
            house.setHouseState("已交房");
            houseService.updateById(house);
            Owner owner = ownerService.getById(ownerId);
            owner.setOwnerHomes(owner.getOwnerHomes() + 1);
            ownerService.updateById(owner);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail();
        }
    }
}